package com.smedi.ismedi.inmail.core.application.service.impl;

import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushBatchDTO;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.inmail.core.application.command.NotificationMessageCommand;
import com.smedi.ismedi.inmail.core.application.command.TransmissionMessageCommand;
import com.smedi.ismedi.inmail.core.application.service.AppPushApplicationService;
import com.smedi.ismedi.inmail.core.domain.aggregatemodel.apppush.AppPushRecord;
import com.smedi.ismedi.inmail.core.domain.repository.AppPushRecordRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AppPushApplicationServiceImpl implements AppPushApplicationService {
    private final AuthorityUtil authorityUtil;
    private final AppPushRecordRepository appPushRecordRepository;

    @Value("${app.push.app.id}")
    private String appId;
    @Value("${app.push.app.key}")
    private String appKey;
    @Value("${app.push.app.secret}")
    private String appSecret;
    @Value("${app.master.secret}")
    private String masterSecret;
    @Value("${getui.url}")
    private String geTuiUrl;

    //透传单推
    @Override
    public String pushPassThroughMessageSingle(TransmissionMessageCommand passThroughMessageCommand) {
        PushDTO pushDTO = this.dtoPassThroughMessage(passThroughMessageCommand);

        return this.push(pushDTO, passThroughMessageCommand.getClientIds(), passThroughMessageCommand.getThirdTitle(), passThroughMessageCommand.getTransmissionContent());
    }

    //透传批量推
    @Override
    public String pushPassThroughMessageBatch(TransmissionMessageCommand passThroughMessageCommand) {
        PushDTO pushDTO = this.dtoPassThroughMessage(passThroughMessageCommand);
        PushBatchDTO pushBatchDTO = new PushBatchDTO();

        pushDTO.setRequestId(System.currentTimeMillis() + "");
        /*设置接收人信息*/
        Audience audience = new Audience();
        for (String cid : passThroughMessageCommand.getClientIds()) {
            audience.setCid(Arrays.asList(cid));
            pushDTO.setAudience(audience);
            pushBatchDTO.addPushDTO(pushDTO);
        }

        return this.pushBatch(pushBatchDTO, passThroughMessageCommand);
    }

    private String pushBatch(PushBatchDTO pushBatchDTO, TransmissionMessageCommand passThroughMessageCommand) {
        AppPushRecord appPushRecord = new AppPushRecord();
        appPushRecord.setContent(passThroughMessageCommand.getTransmissionContent());
        PushApi pushApi = this.createApi();
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushBatchByCid(pushBatchDTO);
        if (apiResult.isSuccess()) {
            // success
            for (PushDTO<Audience> pushDTO : pushBatchDTO.getMsgList()) {
                appPushRecord.setClientIds(pushDTO.getAudience().getCid().toString());
                appPushRecord.setPushTime(LocalDateTime.now());
                appPushRecordRepository.doInsert(appPushRecord);
            }

            return apiResult.getData().toString();
        } else {
            // failed
            String l1 = "code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg();
            appPushRecord.setErrorMsg(l1);
            for (PushDTO<Audience> pushDTO : pushBatchDTO.getMsgList()) {
                appPushRecord.setClientIds(pushDTO.getAudience().getCid().toString());
                appPushRecord.setPushTime(LocalDateTime.now());
                appPushRecordRepository.doInsert(appPushRecord);
            }
            return l1;
        }
    }

    @Override
    public String pushNotificationMessage(NotificationMessageCommand notificationMessageCommand) {
        PushDTO pushDTO = this.dtoNotificationMessage(notificationMessageCommand);

        return this.push(pushDTO, notificationMessageCommand.getClientIds(), notificationMessageCommand.getNotificationTitle(), notificationMessageCommand.getNotificationBody());
    }

    private String push(PushDTO pushDTO, List<String> clientIds, String title, String content) {
        AppPushRecord appPushRecord = new AppPushRecord();
        appPushRecord.setTitle(title);
        appPushRecord.setContent(content);
        PushApi pushApi = this.createApi();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        /*设置接收人信息*/
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.setCid(clientIds);
        /*设置接收人信息结束*/
        //根据cid进行单推
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success

            appPushRecord.setClientIds(clientIds.toString());
            appPushRecord.setPushTime(LocalDateTime.now());
            appPushRecordRepository.doInsert(appPushRecord);
            return apiResult.getData().toString();
        } else {
            // failed
            String l1 = "code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg();
            appPushRecord.setClientIds(clientIds.toString());
            appPushRecord.setErrorMsg(l1);
            appPushRecord.setPushTime(LocalDateTime.now());
            appPushRecordRepository.doInsert(appPushRecord);
            return l1;
        }
    }


    private PushDTO dtoPassThroughMessage(TransmissionMessageCommand transmissionMessageCommand) {

        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        // 设置推送参数

        /**** 设置个推通道参数 *****/
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        //透传消息
        pushMessage.setTransmission(transmissionMessageCommand.getTransmissionContent());
        /**** 设置个推通道参数，更多参数请查看文档或对象源码 *****/

        /**** 设置厂商相关参数 ****/
        PushChannel pushChannel = new PushChannel();
        pushDTO.setPushChannel(pushChannel);
        /*配置安卓厂商参数*/
        AndroidDTO androidDTO = new AndroidDTO();
        pushChannel.setAndroid(androidDTO);
        Ups ups = new Ups();
        androidDTO.setUps(ups);
        ThirdNotification thirdNotification = new ThirdNotification();
        ups.setNotification(thirdNotification);
        thirdNotification.setTitle(transmissionMessageCommand.getThirdTitle());
        thirdNotification.setBody(transmissionMessageCommand.getThirdBody());
        thirdNotification.setClickType(transmissionMessageCommand.getThirdClickType());
        thirdNotification.setUrl(transmissionMessageCommand.getThirdUrl());

        return pushDTO;
    }

    private PushDTO dtoNotificationMessage(NotificationMessageCommand notificationMessageCommand) {
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        // 设置推送参数
        /**** 设置个推通道参数 *****/
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        //通知消息
        GTNotification notification = new GTNotification();
        pushMessage.setNotification(notification);

        notification.setTitle(notificationMessageCommand.getNotificationTitle());
        notification.setBody(notificationMessageCommand.getNotificationBody());
        notification.setClickType(notificationMessageCommand.getClickType());
        notification.setUrl(notificationMessageCommand.getActionUrl());

        return pushDTO;
    }


    private PushApi createApi() {
        // 设置httpClient最大连接数，当并发较大时建议调大此参数。或者启动参数加上 -Dhttp.maxConnections=200
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        //填写应用配置
        apiConfiguration.setAppId(appId);
        apiConfiguration.setAppKey(appKey);
        apiConfiguration.setMasterSecret(masterSecret);
        // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
        apiConfiguration.setDomain(geTuiUrl);
        // 实例化ApiHelper对象，用于创建接口对象
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
        PushApi pushApi = apiHelper.creatApi(PushApi.class);

        return pushApi;
    }
}
